<template>
  <div class="admin-container">
    <!-- 顶部导航栏 -->
    <div class="admin-header">
      <div class="logo-group">
        <img src="@/assets/whu_logo.ico" class="logo" @click="$router.push('/')"/>
        <div class="title">讯航News - 管理员后台</div>
      </div>
      <div class="search-group">
        <el-input
          v-model="searchText"
          placeholder="搜索新闻标题/作者"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
        <el-button type="danger" @click="router.push('/')" class="logout-btn">
          退出登录
        </el-button>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="admin-main">
      <!-- 左侧分类导航 -->
      <div class="admin-sidebar">
        <div 
          v-for="type in newsTypes" 
          :key="type.id"
          :class="['type-item', { active: activeCategory === type.id }]"
          @click="handleCategoryChange(type.id)"
        >
          {{ type.name }}
        </div>
      </div>

      <!-- 右侧内容区 -->
      <div class="admin-content">
        <!-- 操作按钮组 -->
        <div class="action-bar">
          <el-button-group>
            <el-button 
              type="primary" 
              @click="handleBatchPublish(true)" 
              :disabled="selectedIds.length === 0"
            >
              <el-icon><Top /></el-icon> 批量发布
            </el-button>
            <el-button 
              type="warning" 
              @click="handleBatchPublish(false)" 
              :disabled="selectedIds.length === 0"
            >
              <el-icon><Bottom /></el-icon> 批量下架
            </el-button>
            <el-button 
              type="danger" 
              @click="handleBatchDelete" 
              :disabled="selectedIds.length === 0"
            >
              <el-icon><Delete /></el-icon> 批量删除
            </el-button>
          </el-button-group>

        </div>

        <!-- 新闻表格 -->
        <el-table
          :data="newsList"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
          v-loading="loading"
          height="calc(100vh - 220px)"
        >
          <el-table-column type="selection" width="55" />
          <!-- 新增的封面图列 -->
          <el-table-column label="封面图" width="150">
            <template #default="{ row }">
              <el-image
                v-if="row.images"
                style="width: 120px; height: 80px; border-radius: 4px;"
                :src="row.images"
                :preview-src-list="[row.images]"
                fit="cover"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <span v-else class="no-image">无封面</span>
            </template>
          </el-table-column>          
          <el-table-column prop="title" label="标题" width="220" show-overflow-tooltip />

          <el-table-column prop="author" label="作者" width="120" />
          <el-table-column label="分类" width="120">
            <template #default="{ row }">
              {{ getTypeName(row.typeId) }}
            </template>
          </el-table-column>
          <el-table-column prop="submitTime" label="发布时间" width="180" sortable />
          <el-table-column prop="pageviews" label="浏览量" width="100" sortable />
          <el-table-column label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="row.isPublish ? 'success' : 'danger'">
                {{ row.isPublish ? '已发布' : '未发布' }}
                <el-icon v-if="row.ishot" style="margin-left: 5px"><StarFilled /></el-icon>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="290" fixed="right">
            <template #default="{ row }">
              <el-button 
                size="small" 
                :type="row.ishot ? 'warning' : ''"
                @click="toggleHotStatus(row)"
                plain
              >
                <el-icon><Star /></el-icon>
                {{ row.ishot ? '取消热门' : '设为热门' }}
              </el-button>
              <el-button
                size="small"
                :type="row.isPublish ? 'warning' : 'primary'"
                @click="togglePublishStatus(row)"
              >
                {{ row.isPublish ? '下架' : '发布' }}
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(row.id)"
              >
                删除
              </el-button>
              <el-button size="small"
                         type="danger"
                         @click="intoDetailPage(row.id)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="footerPagination">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="prev, pager, next, jumper"
            @current-change="handlePageChange"
            :disabled="loading"
          />
        </div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" :title="editDialogTitle" width="60%">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="新闻标题">
          <el-input v-model="editForm.title"/>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="editForm.author" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="editForm.typeId">
            <el-option
              v-for="type in newsTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="摘要">
          <el-input v-model="editForm.summary" type="textarea" rows="3" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="editForm.detail" type="textarea" rows="10" />
        </el-form-item>
        <el-form-item label="封面图">
          <el-input v-model="editForm.images" placeholder="图片URL" />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="editForm.isPublish">立即发布</el-checkbox>
          <el-checkbox v-model="editForm.ishot">设为热门</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增新闻按钮 -->
    <el-button 
      type="primary" 
      class="add-btn" 
      circle
      @click="handleAddNews"
    >
      <el-icon><Plus /></el-icon>
    </el-button>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import {useRoute, useRouter} from 'vue-router'
import { 
  Search, Top, Bottom, Delete, Refresh, 
  Star, StarFilled, Plus,Picture
} from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'


const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)  // 总页数
// 分页变化处理
const handlePageChange = (newPage) => {
  currentPage.value = 1
  fetchNewsData()
}


const router = useRouter()
const route =useRoute()
const token1=route.query.token
const error=ref(null)
console.log(1);
const intoDetailPage=async (item) => {
  console.log(item);
  try{
    console.log('item',item)
    await router.push({
      path: '/AdminDetailPage', query: {id: item,
        token:token1
      }
    })}
  catch (err){
    error.value = err.response?.data?.message || '失败'
  }
}

// 用户认证
const token = localStorage.getItem('adminToken') || router.currentRoute.value.query.token
if (!token) {
  ElMessage.error('请先登录')
  router.push('/login')
}

// 新闻分类数据
const newsTypes = ref([
  { id: 1, name: '武大资讯' },
  { id: 2, name: '珞珈人物' },
  { id: 3, name: '信息发布' },
  { id: 4, name: '校园生活' }
])

// 表格数据相关
const newsList = ref([])
const loading = ref(false)
const activeCategory = ref(1)
const totalNews = ref(0)
const selectedIds = ref([])
const searchText = ref('')

// 编辑相关
const editDialogVisible = ref(false)
const editDialogTitle = ref('编辑新闻')
const editForm = ref({
  id: null,
  title: '',
  author: '',
  typeId: 1,
  summary: '',
  detail: '',
  images: '',
  isPublish: true,
  ishot: false
})

// 获取分类名称
const getTypeName = (typeId) => {
  return newsTypes.value.find(t => t.id === typeId)?.name || '未知'
}

// 获取新闻数据
const fetchNewsData = async () => {
  loading.value = true
  try {
    const params = {
      tid: activeCategory.value,
      current: currentPage.value,
      pageSize: pageSize.value,
    }

    if (searchText.value) {
      params.search = searchText.value
    }

    const res = await axios.get('http://localhost:8080/news/type', {
      params,
      headers: { Authorization: token }
    })

    newsList.value = res.data.data
    total.value = res.data.total
  } catch (error) {
    if (error.response?.status === 401) {
      handleLogout()
    }
    console.error('获取新闻失败:', error)
    ElMessage.error('获取新闻数据失败')
  } finally {
    loading.value = false
  }
}

// 分类切换
const handleCategoryChange = (typeId) => {
  activeCategory.value = typeId
  currentPage.value = 1
  fetchNewsData()
}



// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchNewsData()
}

// 重置筛选
const resetFilters = () => {
  searchText.value = ''
  timeRange.value = []
  currentPage.value = 1
  fetchNewsData()
}

// 分页大小变化
const handleSizeChange = (size) => {
  searchText.value = ''
  currentPage.value = 1
  fetchNewsData()
}

// 表格多选
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}


// 批量发布/下架（保持原函数名和参数不变）
const handleBatchPublish = async (isPublish) => {
  try {
    // 改用并行单条更新方式（根据您的接口文档）
    await Promise.all(selectedIds.value.map(id => 
      axios.put('http://localhost:8080/news', {
        ...newsList.value.find(item => item.id === id),
        isPublish
      }, {
        headers: { Authorization: token }
      })
    ))
    ElMessage.success(`已${isPublish ? '发布' : '下架'} ${selectedIds.value.length} 条新闻`)
    fetchNewsData()
    selectedIds.value = []
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

// 批量删除（完全保留原函数名和确认对话框）
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定删除选中的 ${selectedIds.value.length} 条新闻吗？`, '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
      customClass: 'batch-delete-message'
    })
    
    // 改用并行单条删除（根据接口文档）
    await Promise.all(selectedIds.value.map(id => 
      axios.delete(`http://localhost:8080/news/${id}`, {
        headers: { Authorization: token }
      })
    ))
    
    ElMessage.success(`已删除 ${selectedIds.value.length} 条新闻`)
    fetchNewsData()
    selectedIds.value = []
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

// 单条发布状态切换（保持原函数名和参数）
const togglePublishStatus = async (row) => {
  try {
    // 调整为完整对象更新（根据接口文档）
    await axios.put('http://localhost:8080/news', {
      ...row,
      isPublish: !row.isPublish
    }, {
      headers: { Authorization: token }
    })
    ElMessage.success(`已${!row.isPublish ? '发布' : '下架'}新闻`)
    fetchNewsData()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

// 单条热门状态切换（保持原函数名）
const toggleHotStatus = async (row) => {
  try {
    // 调整为完整对象更新
    await axios.put('http://localhost:8080/news', {
      ...row,
      ishot: !row.ishot
    }, {
      headers: { Authorization: token }
    })
    ElMessage.success(`已${!row.ishot ? '设为' : '取消'}热门新闻`)
    fetchNewsData()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

// 单条删除（保持原函数名和确认对话框）
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除这条新闻吗？删除后不可恢复！', '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await axios.delete(`http://localhost:8080/news/${id}`, {
      headers: { Authorization: token }
    })
    
    ElMessage.success('删除成功')
    fetchNewsData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

// 编辑/新增相关函数保持完全不变
const handleEdit = (news) => {
  editDialogTitle.value = '编辑新闻'
  editForm.value = { ...news }
  editDialogVisible.value = true
}

const handleAddNews = () => {
  editDialogTitle.value = '新增新闻'
  editForm.value = {
    id: null,
    title: '',
    author: '',
    typeId: 1,
    summary: '',
    detail: '',
    images: '',
    isPublish: true,
    ishot: false
  }
  editDialogVisible.value = true
}

// 编辑提交（保持原函数名）
const handleEditSubmit = async () => {
  try {
    if (editForm.value.id) {
      await axios.put('http://localhost:8080/news', editForm.value, {
        headers: { Authorization: token }
      })
      ElMessage.success('更新成功')
    } else {
      await axios.post('http://localhost:8080/news', editForm.value, {
        headers: { Authorization: token }
      })
      ElMessage.success('添加成功')
    }
    editDialogVisible.value = false
    fetchNewsData()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('adminToken')
  router.push('/login')
}

// 初始化加载
onMounted(() => {
  if (token) {
    localStorage.setItem('adminToken', token)
    fetchNewsData()
  }
})
</script>

<style scoped>
.admin-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.admin-header {
  height: 60px;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  z-index: 1000;
}

.logo-group {
  display: flex;
  align-items: center;
}

.logo {
  height: 40px;
  margin-right: 15px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 15px;
}

.logout-btn {
  margin-left: 15px;
}

.admin-main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.admin-sidebar {
  width: 180px;
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
  overflow-y: auto;
  padding: 15px 0;
}

.type-item {
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.3s;
  color: #666;
}

.type-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.type-item.active {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: bold;
  border-right: 3px solid #409eff;
}

.admin-content {
   flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  width: calc(100% - 180px); /* 减去左侧导航栏宽度 */
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.add-btn {
  position: fixed;
  left: 40px;
  bottom: 40px;
  width: 60px;
  height: 60px;
  font-size: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
}

/* 小屏幕适配 */
@media (max-width: 768px) {
  .admin-header {
    flex-direction: column;
    height: auto;
    padding: 10px;
  }
  
  .logo-group {
    margin-bottom: 10px;
  }
  
  .search-group {
    width: 100%;
  }
  
  .admin-main {
    flex-direction: column;
  }
  
  .admin-sidebar {
    width: 100%;
    display: flex;
    overflow-x: auto;
    padding: 0;
  }
  
  .type-item {
    white-space: nowrap;
    padding: 10px 15px;
  }
  
  .action-bar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-group {
    width: 100%;
    margin-top: 10px;
  }
}
</style>

<style>
/* 全局覆盖 */
.batch-delete-message .el-message-box__message {
  color: #f56c6c;
  font-weight: bold;
}

.el-table .el-table__cell {
  padding: 8px 0;
}

.el-table .cell {
  padding: 0 10px;
}

.el-table {
  flex: 1; /* 让表格填充剩余空间 */
  width: 100% !important; /* 确保宽度100% */
  min-width: 100%; /* 防止内容溢出 */
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.no-image {
  color: #999;
  font-size: 12px;
}


/* 页脚分页样式 - 与新闻列表页面一致 */
.footerPagination {
  position: fixed;
  bottom: 1.25rem;
  left: 180px; /* 与侧边栏宽度一致 */
  right: 0;
  background: #fff;
  padding: 0.9375rem 0;
  display: flex;
  justify-content: center;
  box-shadow: 0 -0.125rem 0.625rem rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.el-pagination {
  --el-pagination-font-size: 1.125rem !important;
}

.admin-content {
  padding-bottom: 5rem !important; /* 给分页留出空间 */
}
</style>